<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getBuildingListAPI, createBuildingListAPI, delBuildingListAPI, editBuildingListAPI } from '@/api/building'
import { utils, writeFileXLSX } from 'xlsx';
import {Delete,Edit,Star} from '@element-plus/icons-vue'
// 表单数据
const addForm = reactive({
  name: '',
  floors: null,
  area: null,
  propertyFeePrice: null,
  id: null
});
// 表单校验规则
const addFormRules = reactive({
  name: [
    { required: true, message: '请输入楼宇名称', trigger: 'blur' }
  ],
  floors: [
    { required: true, message: '请输入楼宇层数', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入楼宇面积', trigger: 'blur' }
  ],
  propertyFeePrice: [
    { required: true, message: '请输入楼宇物业费', trigger: 'blur' }
  ]
});
const addFormRefs = ref(null)
const buildingList = ref([]); // table列表
const params = reactive({ // 请求参数
  page: 1,
  pageSize: 10,
  name: '' // 增加字段name
});
const total = ref(0);
const dialogVisible = ref(false);

onMounted(() => {
  getBuildingList();
});
// 获取楼宇数据
const getBuildingList = async () => {
  const res = await getBuildingListAPI(params);
  buildingList.value = res.data.rows;
  total.value = res.data.total;
};
// 获取楼宇状态
const formatStatus = (status) => {
  const statusMap = {
    0: '租赁中',
    1: '闲置中'
  };
  return statusMap[status] || '未知状态';
};
// 改变页码
const pageChange = (page) => {
  params.page = page;
  getBuildingList();
};
// 搜索
const doSearch = () => {
  params.page = 1;
  getBuildingList();
};
// 添加楼宇信息
const addBuilding = () => {
  dialogVisible.value = true;
  // Object.assign(addForm, { name: '', floors: null, area: null, propertyFeePrice: null});
};
// 关闭弹框，清空数据
const closeDialog = () => {
  dialogVisible.value = false;
  addForm.name = '';
  addForm.floors = null;
  addForm.area = null;
  addForm.propertyFeePrice = null;
};
// 添加/ 修改楼宇数据
const confirmAdd = async () => {
  if (addForm.id) {
    await editBuildingListAPI(addForm);
    ElMessage.success('楼宇信息修改成功');
  } else {
    console.log(addForm);
    delete addForm.id
    await createBuildingListAPI(addForm);
    ElMessage.success('楼宇信息添加成功');
  }
  getBuildingList();
  dialogVisible.value = false;
};
// 删除楼宇
const confirmDel = async (id) => {
  ElMessageBox.confirm(
    '确认删除当前楼宇吗？',
    '温馨提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then( async () => {
      await delBuildingListAPI(id);
      getBuildingList();
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '操作失败',
      })
    })
};
// 修改楼宇
const edit = (row) => {
  dialogVisible.value = true;
  console.log(row);
  delete row.status
  Object.assign(addForm, {...row });
};

const exportToExcel = async () => {
  const res = await getBuildingListAPI(params);
  const tableHeader = ['楼宇名称', '层数', '在管面积(㎡)', '物业费(㎡)', '状态'];
  const sheetData = res.data.rows.map(item => {
    return {
      name: item.name,
      floors: item.floors,
      area: item.area,
      propertyFeePrice: item.propertyFeePrice,
      status: formatStatus(item.status)
    };
  });
  const worksheet = utils.json_to_sheet(sheetData);
  const workbook = utils.book_new();
  utils.book_append_sheet(workbook, worksheet, 'Data');
  utils.sheet_add_aoa(worksheet, [tableHeader], { origin: -1 });
  writeFileXLSX(workbook, 'BuildingData.xlsx');
};
</script>


<template>
  <div class="building-container" style="padding: 20px;">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" @clear="doSearch" />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>
    <!-- 添加楼宇区域 -->
    <el-dialog
      ref="addFormRefs"
      title="添加楼宇"
      v-model="dialogVisible"
      width="580px"
      @close="closeDialog"
    >
      <!-- 表单接口 -->
      <div class="form-container">
        <el-form ref="addFormRefs" :model="addForm" :rules="addFormRules">
          <el-form-item label="楼宇名称" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors">
            <el-input v-model="addForm.floors" />
          </el-form-item>
          <el-form-item label="在管面积" prop="area">
            <el-input v-model="addForm.area" />
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <el-input v-model="addForm.propertyFeePrice" />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button  @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>

    <el-button type="primary" @click="addBuilding">添加楼宇</el-button>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="buildingList"
      >
        <el-table-column
          type="index"
          label="序号"
          min-width="100"
        />
        <el-table-column
          label="楼宇名称"
          min-width="180"
          prop="name"
        />
        <el-table-column
          label="层数"
          prop="floors"
        />
        <el-table-column
          label="在管面积(m²)"
          min-width="120"
          prop="area"
        />
        <el-table-column
          label="物业费(元/m²)"
          min-width="120"
          prop="propertyFeePrice"
        />
        <el-table-column label="状态" prop="status">
          <template #default="scope">
            {{ formatStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="120"
        >
          <template #default="scope">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                <el-button type="primary" :icon="Edit" circle  @click="edit(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <el-button type="danger" :icon="Delete" circle  @click="confirmDel(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 页面栏分页效果区域 -->
    <div class="page-container">
      <el-pagination
        layout="total, prev, pager, next"
        :total="total"
        @current-change="pageChange"
      />
    </div>
  </div>
</template>



<style lang="scss" scoped>
.department-container {
  padding-left: 10px;
}
.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgba(237, 237, 237, 0.9);
  padding-bottom: 20px;
  .search-label {
    width: 100px;
  }
  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
</style>